<template>
  <q-page>
    <div class="text-weight-bold row items-end q-ma-xs q-gutter-sm">
      拟编辑组件：
      <q-btn color="primary" label="识别选中组件" @click="识别选中组件()" />
      <q-btn color="primary" label="修改组件属性" @click="修改组件属性()" />
    </div>
    <div class="row items-end">
      <!-- <div class="row"> -->
      <q-input
        v-model="主组件属性.组件定义名"
        label="组件定义名"
        label-color="orange"
        outlined
        stack-label
        @keyup.enter="kkyy"
      />
      <q-input
        v-model="主组件属性.动态组件名"
        label="动态组件名"
        label-color="orange"
        outlined
        stack-label
        @keyup.enter="kkyy"
      />
    </div>

    <div class="q-pa-md">
      <q-table
        table-header-class="text-weight-bold text-orange"
        :rows="主组件属性.其他属性"
        :columns="columns"
        row-key="name"
        separator="cell"
        binary-state-sort
        :pagination="{ rowsPerPage: 9 }"
        dense
      >
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td key="key" :props="props">
              {{ props.row.key }}
              <template v-if="props.row.id > 5">
                <!-- <q-popup-edit v-model="props.row.key" v-slot="scope">
              <q-input v-model="props.row.key" dense autofocus/>
              </q-popup-edit> -->
                <q-popup-edit
                  v-model="props.row.key"
                  buttons
                  label-set="保存"
                  label-cancel="取消"
                  :validate="aValidation"
                  @hide="aValidation"
                  v-slot="scope"
                >
                  <q-input
                    v-model="scope.value"
                    :error="errorA"
                    :error-message="errorMessageA"
                    dense
                    autofocus
                    @keyup.enter="scope.set"
                  />
                </q-popup-edit>
              </template>
            </q-td>
            <q-td key="formula" :props="props">
              {{ props.row.formula }}
              <div v-if="props.row.error && props.row.error.includes('error')">
                <span class="text-negative">出错了： </span>
                <span v-html="props.row.error"></span>
              </div>
              <q-popup-edit v-model="props.row.formula" v-slot="scope">
                <q-input
                  v-model="props.row.formula"
                  dense
                  autofocus
                  @keyup.enter="scope.set"
                />
              </q-popup-edit>
            </q-td>
            <q-td key="formlabel" :props="props">
              {{ props.row.formlabel }}
              <q-popup-edit v-model="props.row.formlabel" v-slot="scope">
                <q-input v-model="props.row.formlabel" dense autofocus />
              </q-popup-edit>
            </q-td>
          </q-tr>
        </template>
      </q-table>
    </div>

    <!-- <div class="text-h6">拟引用参数的父子组件：</div> -->
    <div class="row items-end q-mt-md">
      <div class="text-weight-bold col-12">父组件：</div>
      <div class="row">
        <q-input
          class="col-6"
          v-model="父组件属性.组件定义名"
          label="组件定义名"
          label-color="orange"
          outlined
          stack-label
          readonly
        />
        <q-input
          class="col-6"
          v-model="父组件属性.动态组件名"
          label="动态组件名"
          label-color="orange"
          outlined
          stack-label
          readonly
        />
      </div>
      <q-select
        outlined
        v-model="model"
        use-input
        input-debounce="0"
        label="属性全名"
        label-color="orange"
        option-value="key"
        option-label="formlabel"
        :options="父组件属性.其他属性"
        @update:model-value="xuanzewancheng"
        @filter-abort="abortFilterFn"
      >
        <template v-slot:option="scope">
          <q-item v-bind="scope.itemProps">
            <q-item-section>
              <q-item-label caption>{{ scope.opt.key }}</q-item-label>
            </q-item-section>
            <q-item-section>
              <q-item-label caption>{{ scope.opt.formlabel }}</q-item-label>
            </q-item-section>
          </q-item>
        </template>
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey"> No results </q-item-section>
          </q-item>
        </template>
        <template v-if="model" #append>
          <q-btn
            color="primary"
            round
            dense
            flat
            icon="content_copy"
            @click.stop.prevent="复制内容(model)"
          >
            <q-tooltip> 复制 </q-tooltip>
          </q-btn>
        </template>
      </q-select>
    </div>
    <div class="row items-end q-mt-md">
      <div class="text-weight-bold col-12">兄弟组件或子组件：</div>
      <div class="row">
        <q-select
          class="col-6"
          outlined
          v-model="相关组件model"
          use-input
          input-debounce="0"
          label="组件定义名"
          label-color="orange"
          option-value="动态组件名"
          option-label="组件定义名"
          :options="相关组件属性"
        >
          <template v-slot:option="scope">
            <q-item v-bind="scope.itemProps">
              <q-item-section>
                <q-item-label caption>{{ scope.opt.组件定义名 }}</q-item-label>
              </q-item-section>
              <q-item-section>
                <q-item-label caption>{{ scope.opt.动态组件名 }}</q-item-label>
              </q-item-section>
            </q-item>
          </template>
          <template v-slot:no-option>
            <q-item>
              <q-item-section class="text-grey"> No results </q-item-section>
            </q-item>
          </template>
        </q-select>
        <q-input
          class="col-6"
          v-model="具体相关组件动态名"
          label="动态组件名"
          label-color="orange"
          outlined
          stack-label
          readonly
        />
      </div>
      <q-select
        outlined
        v-model="相关组件属性model"
        use-input
        input-debounce="0"
        label="属性全名"
        label-color="orange"
        option-value="key"
        option-label="formlabel"
        :options="具体相关组件.其他属性"
        @update:model-value="xuanzewancheng2"
      >
        <template v-slot:option="scope">
          <q-item v-bind="scope.itemProps">
            <q-item-section>
              <q-item-label caption>{{ scope.opt.key }}</q-item-label>
            </q-item-section>
            <q-item-section>
              <q-item-label caption>{{ scope.opt.formlabel }}</q-item-label>
            </q-item-section>
          </q-item>
        </template>
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey"> No results </q-item-section>
          </q-item>
        </template>
        <template v-if="相关组件属性model" #append>
          <q-btn
            color="primary"
            round
            dense
            flat
            icon="content_copy"
            @click.stop.prevent="复制内容(model)"
          >
            <q-tooltip> 复制 </q-tooltip>
          </q-btn>
        </template>
      </q-select>
    </div>
  </q-page>
</template>

<!-- <script>
defineComponent({
  name: '动态组件'
})
</script> -->

<script setup>
import { defineComponent, computed } from "vue";
import { ref, toRefs, reactive } from "vue";
import { copyToClipboard } from "quasar";
import { useQuasar } from "quasar";

import useClient from "../hooks/useClient";
const { store, storeToRefs } = useClient(ws);

const { 主组件属性 } = storeToRefs(store);
console.log("主组件属性", 主组件属性);
console.log("store.主组件属性", store.主组件属性);

const { 父组件属性 } = storeToRefs(store);
// const 父组件属性 = store.父组件属性
console.log("父组件属性", 父组件属性);
console.log("父组件属性.其他属性", 父组件属性.value.其他属性);

const { 相关组件属性 } = storeToRefs(store);

const $q = useQuasar();
function 识别选中组件() {
  ws.send(JSON.stringify({ sketchup: "识别选中组件" }));
  // ws.send('something');
}
function 修改组件属性() {
  ws.send(
    JSON.stringify({ sketchup: "修改组件属性", 主组件属性: 主组件属性.value })
  );
}
function showNotif(message, position) {
  $q.notify({
    message,
    color: "primary",
    timeout: 50,
    position,
  });
}

// const options= [
//         {
//           key: 'goog',
//           formlabel: 'Google'
//         },
//         {
//           key: 'fb',
//           formlabel: 'Facebook'
//         },
//         ]
function 复制内容(params) {
  copyToClipboard(params)
    .then(() => {
      showNotif(`${params} 已复制`, "center");
    })
    .catch(() => {
      // 失败
    });
}

const model = ref(null);
const 相关组件model = ref(null);
const 相关组件属性model = ref(null);
let 具体相关组件 = {};
function xuanzewancheng(params) {
  // console.log(params);
  let 全名 = `${父组件属性.value.动态组件名}!${params.key}`;
  console.log(全名);
  model.value = 全名;
  复制内容(全名);
  // alert(params);
}
function xuanzewancheng2(params) {
  console.log(params);
  let 全名 = `${具体相关组件.动态组件名}!${params.key}`;
  console.log(全名);
  相关组件属性model.value = 全名;
  复制内容(全名);
  // alert(params);
}
const 具体相关组件动态名 = computed(() => {
  if (相关组件model.value) {
    console.log(相关组件model.value.组件定义名);

    具体相关组件= 相关组件属性.value.filter((p) => {
      return p.组件定义名.indexOf(相关组件model.value.组件定义名) !== -1;
    })[0];
    // console.log("对应组件",对应组件);
    return 具体相关组件.动态组件名
  }
});



function filterFn(val, update, abort) {
  // call abort() at any time if you can't retrieve data somehow
  alert(ref);
  // setTimeout(() => {
  //   update(
  //     () => {
  //       if (val === "") {
  //         options.value = stringOptions;
  //       } else {
  //         const needle = val.toLowerCase();
  //         options.value = stringOptions.filter(
  //           (v) => v.toLowerCase().indexOf(needle) > -1
  //         );
  //       }
  //     },

  //     // "ref" is the Vue reference to the QSelect
  //     (ref) => {
  //       if (val !== "" && ref.options.length > 0) {
  //         ref.setOptionIndex(-1); // reset optionIndex in case there is something selected
  //         ref.moveOptionSelection(1, true); // focus the first selectable option and do not update the input-value
  //       }
  //     }
  //   );
  // }, 300);
}

function filterFnAutoselect(val, update, abort) {
  // call abort() at any time if you can't retrieve data somehow

  setTimeout(() => {
    update(
      () => {
        if (val === "") {
          options.value = stringOptions;
        } else {
          const needle = val.toLowerCase();
          options.value = stringOptions.filter(
            (v) => v.toLowerCase().indexOf(needle) > -1
          );
        }
      },

      // "ref" is the Vue reference to the QSelect
      (ref) => {
        if (
          val !== "" &&
          ref.options.length > 0 &&
          ref.getOptionIndex() === -1
        ) {
          ref.moveOptionSelection(1, true); // focus the first selectable option and do not update the input-value
          ref.toggleOption(ref.options[ref.optionIndex], true); // toggle the focused option
        }
      }
    );
  }, 300);
}

function abortFilterFn() {
  console.log("delayed filter aborted");
}

const input = ref("");
const date = ref("2018/11/03");

const group = ref(null);

const columns = [
  {
    name: "key",
    label: "属性名",
    align: "center",
    required: true,
    field: (row) => row.key,
    format: (val) => `${val}`,
  },
  {
    name: "formula",
    align: "center",
    label: "公式值",
    field: "formula",
    sortable: true,
  },
  {
    name: "formlabel",
    align: "center",
    label: "标签名",
    field: "formlabel",
    sortable: true,
  },
];

// const rows = ref(主组件属性.value.其他属性)
const errorA = ref(false);
const errorMessageA = ref("");
function aValidation(val) {
  console.log("验证", val);
  let regu = "^[A-Za-z]+\w*$";
  let re = new RegExp(regu);
  console.log(re.test(val));
  // console.log(!re.test(val));
  if (!re.test(val)) {
    console.log("false");
    errorA.value = true;
    errorMessageA.value =
      "属性名只能是字母、数字和 _ ,且不能以 _ 和 数字 开头！";
    return false;
  }
  console.log("true");
  errorA.value = false;
  errorMessageA.value = "";
  return true;
}

function kkyy(e) {
  // @keyup.enter="$event.target.blur"
  // console.log(e.target);
  e.target.blur();
}

let 组件定义名 = ref("阿弥陀佛");
let 动态组件名 = ref("阿弥陀佛动态组件名");
// export default {
//   setup () {
//     return {
//       columns,
//       rows: ref(rows)
//     }
//   }
// }
</script>

<style lang="scss">
.subformula-error {
  color: $negative !important;
}
</style>
